package br.ufal.tci.nexos.arcolive.logger;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;

public class ArCoLIVELogRepository {

	private ArrayList repository;
	private static ArCoLIVELogRepository singleton;
	private ArrayList listeners;
	
	private ArCoLIVELogRepository() {
		this.repository = new ArrayList();
		this.listeners = new ArrayList();
	}
	
	public static ArCoLIVELogRepository getInstance() {
		if (singleton == null) {
			singleton = new ArCoLIVELogRepository();
		}
		
		return singleton;
	}
	
	public void addListener(ArCoLIVELogRepositoryListener listener) {
		this.listeners.add(listener);
	}
	
	public void log(String log) {
		this.repository.add(log);
		for (Iterator iter = listeners.iterator(); iter.hasNext();) {
			((ArCoLIVELogRepositoryListener) iter.next()).notifyLog(log);			
		}
	}
	
	public void log(Object log) {
		this.repository.add(log);
		for (Iterator iter = listeners.iterator(); iter.hasNext();) {
			((ArCoLIVELogRepositoryListener) iter.next()).notifyLog(log.toString());			
		}
	}
	
	public String toString() {
		Iterator iter = this.repository.iterator();
		String result = "";
		while (iter.hasNext()) {
			String aLog = (String) iter.next();
			result = result + '\n' + aLog;
		}
			
		return result;
	}
	
	public void store(PrintWriter output) {
		output.print(this.toString());
		output.flush();
	}
	
}
